//
//  SetupViewController.m
//  APJ HRadar
//
//  Created by Richard Zhao on 3/4/14.
//  Copyright (c) 2014 APJ. All rights reserved.
//

#import "SetupViewController.h"
#import "LoginViewController.h"
#import "syncDataService.h"
#import "webService.h"
#import "Const.h"
#import "Const.h"
#define OK_BREAK @"---------------------------finish----------------------------"
#define NO_BREAK @"---------------------------error-----------------------------"

@interface SetupViewController ()

@end

@implementation SetupViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UITabBarItem *tab = [[UITabBarItem alloc] initWithTitle:@"Setup" image:[UIImage imageNamed:@"tab_setup"] tag:5];
        self.tabBarItem = tab;
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(doHideKeyBoard)];
    
    tap.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer: tap];
    [tap setCancelsTouchesInView:NO];
}

- (void)doHideKeyBoard{
    [serverAddress resignFirstResponder];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self updateSyncLabel];
    [self loadServerAddress];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) setTabBarEnabled:(BOOL) enabled
{
    UITabBar *myTb=self.tabBarController.tabBar;
    for(UITabBarItem *utb in myTb.items)
    {
        utb.enabled=enabled;
    }
}

- (void) syncActionLog:(float)perProgress withTableArray:(NSArray *)tableArray {
    // 异步线程，防止UI被卡
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //syncBool = [[syncDataService sharedService] doSyncTableFromActionLog];
        float progress = 0.0f;
        __block NSString *yesOrNo;
        BOOL syncSuccess = YES;
        BOOL success = YES;
        for (int i = 0 ; i < [tableArray count]; i ++) {
            syncSuccess = [[syncDataService sharedService] doPreSyncTableFromActionLog:i];
            if (!syncSuccess) {
                success = NO;
            }
            progress += perProgress;
            // 同步线程，更新UI
            dispatch_sync(dispatch_get_main_queue(), ^{
                [syncProgressView setProgress:progress];
                if (syncSuccess) {
                    yesOrNo = @"YES";
                } else {
                    yesOrNo = @"NO";
                }
                [showTextView setText:[NSString stringWithFormat:@"%-58s%@\n%@", [tableArray[i] cStringUsingEncoding:NSASCIIStringEncoding], yesOrNo, [showTextView text]]];
                [showTextView setFont:[UIFont fontWithName:@"Courier New" size:16]];
            });
        }
        syncSuccess = [[syncDataService sharedService] doPreSyncTableFromActionLog:-1];
        if (syncSuccess) {
            yesOrNo = @"YES";
        } else {
            yesOrNo = @"NO";
        }
        if (!syncSuccess) {
            success = NO;
        }
        dispatch_sync(dispatch_get_main_queue(), ^{
            [showTextView setText:[NSString stringWithFormat:@"%-58s%@\n%@", [@"Staff's Photo" cStringUsingEncoding:NSASCIIStringEncoding], yesOrNo, [showTextView text]]];
            [showTextView setFont:[UIFont fontWithName:@"Courier New" size:16]];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setTabBarEnabled:YES];
            [logoutButton setEnabled:YES];
            [syncButton setEnabled:YES];
            [syncProgressView setProgress:progress];
            if (success) {
                [showTextView setText:[NSString stringWithFormat:@"%@\n%@", OK_BREAK, [showTextView text]]];
                [self updateSyncLabel];
            } else {
                [showTextView setText:[NSString stringWithFormat:@"%@\n%@", NO_BREAK, [showTextView text]]];
            }
            [showTextView setFont:[UIFont fontWithName:@"Courier New" size:16]];
        });
    });
}

- (void) syncWebService:(float)preProgress withTableArray:(NSArray *)tableArray {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // syncBool = [[syncDataService sharedService] doSyncDataFromWebService];
        float progress = 0.0f;
        __block NSString *yesOrNo;
        BOOL syncSuccess = YES;
        BOOL success = YES;
        for (int i = 0 ; i < [tableArray count]; i ++) {
            syncSuccess = [[syncDataService sharedService] doPreSyncTableFromWebService:i];
            if (!syncSuccess) {
                success = NO;
            }
            progress += preProgress;
            // 同步线程，更新UI
            dispatch_sync(dispatch_get_main_queue(), ^{
                [syncProgressView setProgress:progress];
                if (syncSuccess) {
                    yesOrNo = @"YES";
                } else {
                    yesOrNo = @"NO";
                }
                [showTextView setText:[NSString stringWithFormat:@"%-58s%@\n%@", [tableArray[i] cStringUsingEncoding:NSASCIIStringEncoding], yesOrNo, [showTextView text]]];
                [showTextView setFont:[UIFont fontWithName:@"Courier New" size:16]];
            });
        }
        if (syncSuccess) {
            yesOrNo = @"YES";
        } else {
            yesOrNo = @"NO";
        }
        if (!syncSuccess) {
            success = NO;
        }
        syncSuccess = [[syncDataService sharedService] doPreSyncTableFromWebService:-1];
        dispatch_sync(dispatch_get_main_queue(), ^{
            [showTextView setText:[NSString stringWithFormat:@"%-58s%@\n%@", [@"Staff's Photo" cStringUsingEncoding:NSASCIIStringEncoding], yesOrNo, [showTextView text]]];
            [showTextView setFont:[UIFont fontWithName:@"Courier New" size:16]];
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setTabBarEnabled:YES];
            [logoutButton setEnabled:YES];
            [syncButton setEnabled:YES];
            [syncProgressView setProgress:progress];
            if (success) {
                [showTextView setText:[NSString stringWithFormat:@"%@\n%@", OK_BREAK, [showTextView text]]];
                [self updateSyncLabel];
            } else {
                [showTextView setText:[NSString stringWithFormat:@"%@\n%@", NO_BREAK, [showTextView text]]];
            }
            [showTextView setFont:[UIFont fontWithName:@"Courier New" size:16]];
        });
    });
}

- (IBAction)syncData:(id)sender {
    [self setTabBarEnabled:NO];
    [logoutButton setEnabled:NO];
    [syncButton setEnabled:NO];
    NSArray *tableArray = [[syncDataService sharedService] getSyncTablesNSArray];
    float preProgerss = [self getProgressPerFloat:[tableArray count]];
    [[NSUserDefaults standardUserDefaults] setValue:serverAddress.text forKey:SERVER_ADDRESS_KEY];
    [webService loginAccount:@"admin" withPassword:@"admin"];
    NSTimeInterval syncTimestamp = [[NSUserDefaults standardUserDefaults] doubleForKey:SYNC_TIMESTAMP_KEY];
    // [showTextView setText:@"updating"];
    if (syncTimestamp < 1) {
        [self syncWebService:preProgerss withTableArray:tableArray];
    } else {
        [self syncActionLog:preProgerss withTableArray:tableArray];
    }
}

- (float) getProgressPerFloat:(int) tableCount
{
    float preFloat = 1.0f / (float)tableCount;
    return preFloat;
}

- (IBAction)logout:(id)sender {
    extern BOOL hasLogin;
    hasLogin = NO;
    LoginViewController *login = [[LoginViewController alloc] init];
    [self presentViewController:login animated:YES completion:nil];
}

- (void)loadServerAddress {
    NSString *address = [[NSUserDefaults standardUserDefaults] stringForKey:SERVER_ADDRESS_KEY];
    if (!address || [address isEqualToString:@""]) {
        address = SERVER_ADDRESS_DEFAULT;
    }
    serverAddress.text = address;
}

- (void)updateSyncLabel
{
    NSTimeInterval syncTimestamp = [[NSUserDefaults standardUserDefaults] doubleForKey:SYNC_TIMESTAMP_KEY];
    if (syncTimestamp < 1) {
        lastSyncLabel.text = @"";
        return;
    }
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [format stringFromDate:[NSDate dateWithTimeIntervalSince1970:syncTimestamp]];
    lastSyncLabel.text = [NSString stringWithFormat:@"Last Update Time is %@", dateString];
}

@end
